package view
{
	import data.BulletProp;
	import data.EBulletProp;
	import data.Globals;
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.geom.Point;
	
	import interfaces.IView;
	
	import manager.BulletName;
	import manager.ObjDataManage;
	import manager.ObjectPool;
	import manager.SoundManage;
	
	import view.Arm.BaseTank;
	import view.Arm.tank.CTank;
	import view.base.BaseView;
	import view.base.ClearView;
	import view.bullet.ABullet;
	import view.bullet.BaseBullet;
	import view.bullet.DBullet;
	import view.monster.BaseMonster;
	import view.plant.PlantItem;

	public class BulletView extends ClearView
	{
		private var bulletAry:Array;
		
		public function BulletView()
		{
			bulletAry = [];
		}
		
		override public function clearView():void{
			super.clearView();
			bulletAry.length = 0;
		}
		
		override protected function loop(event:Event):void{
			var i:int = 0;
			var boo:Boolean;
			for(i;i<bulletAry.length;i++){
				var bullet:BaseBullet = bulletAry[i];
				if(bullet.shoutTarget&&!checkTarIsDie(bullet.shoutTarget)){
					bullet.tarPoint = new Point(bullet.shoutTarget.x,bullet.shoutTarget.y);
					bullet.speed = bullet.speed;
				}
				bullet.move();
				bullet.checkHitMonster();
				if(bullet is DBullet){
					boo = true;
				}
			}
			if(boo){
				SoundManage.getInstance().playOrStopLightning(true);
			}
		}
		
		private function checkTarIsDie(tar:DisplayObject):Boolean{
			var boo:Boolean;
			if(tar is BaseMonster){
				Globals.gameView.getMonsterAry().indexOf(tar)==-1 ? boo=true : boo = false;
			}else if(tar is PlantItem){
				Globals.gameView.getPlantAry().indexOf(tar)==-1 ? boo=true : boo =false;
			}
			return boo;
		}
		
		/**
		 *  
		 * @param type
		 * @param p 
		 * @param tar
		 * @param sendTar 发射对象
		 * 
		 */
		public function createBullet(type:String,p:Point,tar:Point,sendTar:BaseTank = null,posX:int=0,posY:int=0,shoutTarget:DisplayObject=null):void{
			var bp:BulletProp = ObjDataManage.getInstance().bulletMap[type];
			var bullet:BaseBullet = ObjectPool.getObj(BulletName.getBulletCls(type)) as BaseBullet;
			bullet.x = p.x;
			bullet.y = p.y;
			bullet.tarPoint = tar;
			bullet.speed = bp.speed;
			bullet.explode = bp.explode;
			bullet.ART = bp.art;
			bullet.shoutTarget = shoutTarget;
			if(bp is EBulletProp){
				bullet.hurtRange = (bp as EBulletProp).hurtRange;
			}
			bullet.onRemove = removeThis;
			bullet.setDisplay(posX,posY);
			this.addChild(bullet);
			if(bullet is DBullet){
				(bullet as DBullet).sendTarget = sendTar;
			}
			bulletAry.push(bullet);
		}
		
		private function removeThis(bullet:BaseBullet):void
		{
			var index:int = bulletAry.indexOf(bullet);
			if(bullet is DBullet){
				((bullet as DBullet).sendTarget as CTank).bullet =false;
			}
			bulletAry.splice(index,1);
		}
	}
}